/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.module.client;

import com.google.common.collect.Sets;

import org.apache.commons.collections4.IteratorUtils;
import org.pajamas.starter.core.util.RegisterAsPajamasClient;
import org.pajamas.starter.integration.spring.bean.BeanConstants;
import org.pajamas.starter.integration.spring.cloud.RestTemplateBuilderCustomizer;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.Iterator;

/**
 * @author william
 * @since 2024/2/5
 */
@RegisterAsPajamasClient.ConfigurationBean
public class PajamasRestClientConfiguration {
    @ConditionalOnProperty(prefix = "org.pajamas.starter.client", value = "restTemplate", havingValue =
            "true", matchIfMissing = true)
    @Order(BeanConstants.ORDER_LATEST_SECOND)
    @Bean
    public RestTemplateBuilderCustomizer pajamasRestTemplateBuilderCustomizer() {
        return builder ->
                builder
                        .setConnectTimeout(Duration.ofSeconds(60))
                        .setReadTimeout(Duration.ofSeconds(60));
    }

    @ConditionalOnMissingBean
    @ConditionalOnBean({RestTemplateBuilder.class, RestTemplateBuilderCustomizer.class})
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder,
                                     ObjectProvider<RestTemplateBuilderCustomizer> customizers) {
        Iterator<RestTemplateBuilderCustomizer> iterator = customizers.orderedStream().iterator();
        if (!IteratorUtils.isEmpty(iterator)) {
            Sets.newHashSet(iterator).forEach(customizer -> customizer.customize(builder));
        }
        return builder.build();
    }
}
